{% extends 'base.html' %}
{% load static %}

{% block title %}{% if page_title %}{{ page_title }}{% else %}全部商品{% endif %} - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .page-header {
        background-color: #f8f9fa;
        padding: 30px 0;
        margin-bottom: 30px;
    }
    
    .page-title {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 10px;
    }
    
    .filter-section {
        margin-bottom: 20px;
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 5px;
    }
    
    .filter-title {
        font-weight: 600;
        margin-bottom: 10px;
    }
    
    .sort-btn {
        padding: 5px 15px;
        border-radius: 15px;
        margin-right: 5px;
        font-size: 14px;
    }
    
    .product-card {
        transition: transform 0.3s, box-shadow 0.3s;
        height: 100%;
    }
    
    .product-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }
    
    .product-img {
        height: 200px;
        object-fit: contain;
        padding: 10px;
    }
    
    .price {
        color: #e74c3c;
        font-weight: bold;
    }
    
    .original-price {
        color: #95a5a6;
        text-decoration: line-through;
        font-size: 0.9rem;
        margin-left: 5px;
    }
    
    .category-card {
        margin-bottom: 15px;
        transition: all 0.3s;
    }
    
    .category-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .category-card .card-title {
        font-weight: 600;
    }
    
    .subcategory-list {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
    }
    
    .subcategory-link {
        font-size: 0.9rem;
        color: #6c757d;
        padding: 2px 8px;
        border-radius: 12px;
        background-color: #f8f9fa;
        text-decoration: none;
    }
    
    .subcategory-link:hover {
        background-color: #007bff;
        color: white;
    }
</style>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<section class="page-header">
    <div class="container">
        <h1 class="page-title">{% if page_title %}{{ page_title }}{% else %}全部商品{% endif %}</h1>
        <p class="text-muted">
            {% if page_title == '新品上架' %}
            发现最新上架的优质商品
            {% elif page_title == '热门促销' %}
            不容错过的超值优惠
            {% else %}
            发现最适合您的商品
            {% endif %}
        </p>
    </div>
</section>

<div class="container">
    <div class="row">
        <!-- 左侧分类导航 -->
        <div class="col-md-3 d-none d-md-block">
            <h5 class="mb-3">商品分类</h5>
            {% for category in categories %}
            <div class="card category-card">
                <div class="card-body p-3">
                    <h6 class="card-title">
                        <a href="{% url 'category' category.id %}" class="text-decoration-none text-dark">{{ category.name }}</a>
                    </h6>
                    <div class="subcategory-list">
                        {% for subcategory in category.subcategories.all|slice:":5" %}
                        <a href="{% url 'subcategory' subcategory.id %}" class="subcategory-link">{{ subcategory.name }}</a>
                        {% endfor %}
                        {% if category.subcategories.count > 5 %}
                        <a href="{% url 'category' category.id %}" class="subcategory-link">更多...</a>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <!-- 右侧商品列表 -->
        <div class="col-md-9">
            <!-- 筛选和排序 -->
            <div class="filter-section">
                <div class="row align-items-center">
                    <div class="col-md-2">
                        <div class="filter-title">排序方式：</div>
                    </div>
                    <div class="col-md-10">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-primary sort-btn active">默认</button>
                            <button type="button" class="btn btn-outline-primary sort-btn">销量 <i class="bi bi-arrow-down"></i></button>
                            <button type="button" class="btn btn-outline-primary sort-btn">价格 <i class="bi bi-arrow-up"></i></button>
                            <button type="button" class="btn btn-outline-primary sort-btn">价格 <i class="bi bi-arrow-down"></i></button>
                            <button type="button" class="btn btn-outline-primary sort-btn">评分 <i class="bi bi-arrow-down"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 商品列表 -->
            <div class="row mb-4">
                {% for product in page_obj %}
                <div class="col-lg-4 col-md-6 col-sm-6 mb-4">
                    <div class="card product-card">
                        <a href="{% url 'product_detail' product.id %}">
                            <img src="" data-src="{{ product.get_main_image_url }}" class="card-img-top product-img lazy-load" alt="{{ product.name }}">
                        </a>
                        <div class="card-body">
                            <h5 class="card-title">
                                <a href="{% url 'product_detail' product.id %}" class="text-decoration-none text-dark">{{ product.name }}</a>
                            </h5>
                            <div class="mb-2">
                                <span class="price">¥{{ product.price }}</span>
                                {% if product.original_price and product.original_price > product.price %}
                                <span class="original-price">¥{{ product.original_price }}</span>
                                {% endif %}
                            </div>
                            <p class="card-text text-muted">{{ product.description|default:product.name|truncatechars:50|safe }}</p>
                        </div>
                        <div class="card-footer bg-white">
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">{{ product.store_name }}</small>
                                <a href="{% url 'product_detail' product.id %}" class="btn btn-sm btn-outline-primary">查看详情</a>
                            </div>
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="col-12">
                    <div class="alert alert-info">暂无商品数据</div>
                </div>
                {% endfor %}
            </div>
            
            <!-- 分页 -->
            {% if page_obj.has_other_pages %}
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page=1" aria-label="First">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <a class="page-link" href="#" aria-label="First">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item disabled">
                        <a class="page-link" href="#" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {% endif %}
                    
                    {% for i in page_obj.paginator.page_range %}
                        {% if page_obj.number == i %}
                        <li class="page-item active"><a class="page-link" href="#">{{ i }}</a></li>
                        {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
                        <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                        {% endif %}
                    {% endfor %}
                    
                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}" aria-label="Last">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <a class="page-link" href="#" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li class="page-item disabled">
                        <a class="page-link" href="#" aria-label="Last">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

<!-- 无限滚动加载指示器 -->
<div id="load-more-indicator" class="text-center py-4" style="display: none;">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
    </div>
    <p class="mt-2">正在加载更多商品...</p>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化懒加载
        initLazyLoad();
        
        // 初始化无限滚动
        initInfiniteScroll();
        
        // 初始化排序按钮
        initSortButtons();
    });
    
    // 无限滚动功能
    function initInfiniteScroll() {
        let loading = false;
        let currentPage = {{ page_obj.number }};
        const totalPages = {{ page_obj.paginator.num_pages }};
        const loadMoreIndicator = document.getElementById('load-more-indicator');
        
        // 如果只有一页，不需要无限滚动
        if (totalPages <= 1) return;
        
        // 滚动事件监听器
        window.addEventListener('scroll', debounce(function() {
            // 检查是否已经到达页面底部
            if (loading || currentPage >= totalPages) return;
            
            // 检查是否接近底部
            const scrollPosition = window.innerHeight + window.scrollY;
            const pageHeight = document.body.offsetHeight;
            const scrollThreshold = pageHeight * 0.85; // 滚动到85%时开始加载更多
            
            if (scrollPosition >= scrollThreshold) {
                loadMoreProducts();
            }
        }, 200));
        
        // 加载更多商品
        function loadMoreProducts() {
            if (loading || currentPage >= totalPages) return;
            
            loading = true;
            if (loadMoreIndicator) loadMoreIndicator.style.display = 'block';
            
            // 下一页
            currentPage++;
            
            // AJAX请求获取下一页数据
            fetch(`?page=${currentPage}&ajax=1`)
                .then(response => response.text())
                .then(html => {
                    // 创建一个临时容器来解析HTML
                    const tempContainer = document.createElement('div');
                    tempContainer.innerHTML = html;
                    
                    // 获取商品容器
                    const productContainer = document.querySelector('.row.mb-4');
                    const newProducts = tempContainer.querySelectorAll('.product-card');
                    
                    // 如果没有找到新商品，可能是页面结构不匹配
                    if (newProducts.length === 0) {
                        console.error('无法找到新商品，请检查页面结构');
                        return;
                    }
                    
                    // 逐个添加商品到容器中
                    newProducts.forEach(product => {
                        const colDiv = document.createElement('div');
                        colDiv.className = 'col-lg-4 col-md-6 col-sm-6 mb-4';
                        colDiv.appendChild(product);
                        productContainer.appendChild(colDiv);
                    });
                    
                    // 重新初始化懒加载
                    initLazyLoad();
                    
                    // 更新URL，但不刷新页面
                    history.replaceState(null, '', `?page=${currentPage}`);
                    
                    // 如果已经到达最后一页，隐藏加载指示器
                    if (currentPage >= totalPages) {
                        if (loadMoreIndicator) loadMoreIndicator.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('加载更多产品时出错:', error);
                })
                .finally(() => {
                    loading = false;
                    if (loadMoreIndicator) loadMoreIndicator.style.display = 'none';
                });
        }
    }
    
    // 初始化排序按钮
    function initSortButtons() {
        const sortButtons = document.querySelectorAll('.sort-btn');
        sortButtons.forEach(button => {
            button.addEventListener('click', function() {
                // 移除所有按钮的激活状态
                sortButtons.forEach(btn => btn.classList.remove('active'));
                // 添加当前按钮的激活状态
            this.classList.add('active');
                
                // 这里可以添加排序逻辑
                // ...
        });
    });
    }
</script>
{% endblock %} 